//
//  LTUpgradeTools.m
//  LearnTeacher
//
//  Created by 高刘通 on 2024/6/17.
//

#import "LTUpgradeTools.h"
#import "UIViewController+Additions.h"
#import "LTUpgradeModel.h"
#import "NSObject+YYModel.h"
#import "LTUpgradePopView.h"

@interface LTUpgradeTools()
@property(assign, nonatomic, getter=isPoped) BOOL poped;
@end

@implementation LTUpgradeTools

+ (instancetype)shared {
    static LTUpgradeTools *tools = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tools = [[self alloc] init];
    });
    return tools;
}

- (void)checkTeacherversion {
    if (self.isPoped) {
        return; //非强制升级只弹一次
    }
    NSString *url = [NSString stringWithFormat:@"%@%@",BASE_URL,CHECK_TEACHER_VERSION];
    NSDictionary *parms = @{
        @"platform":@"ios",
        @"current_version":[self version]
    };
    __weak typeof(self) weakSelf = self;
    [BaseRequest netIgnorePOST:url cache:NO autoHideLoading:NO parms:parms result:^(id resultObject, NSError *error) {
        NSLog(@"版本升级 - %@", resultObject);
        if (resultObject && [resultObject[@"code"] doubleValue] == 1) {
            id data = resultObject[@"data"];
            if ([data isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dataDict = (NSDictionary *)data;
                if (dataDict.count > 0) {
                    NSString *message = [NSString stringWithFormat:@"%@", dataDict[@"version"]];
                    LTUpgradeModel *model = [LTUpgradeModel modelWithJSON:dataDict];
                    if ([model.enforce intValue] == 1) { //强制升级
                        [weakSelf forceUpdate:message content:model.content url:model.downloadurl];
                    }else { //可选升级
                        weakSelf.poped = YES;
                        [weakSelf optionalUpdate:message content:model.content url:model.downloadurl];
                    }
                }
            }
        }
    }];
}

- (void)ignoreUpdate {
    
}

- (NSString *)saveKey {
    return [NSString stringWithFormat:@"user_key_%@", [self version]];
}

- (NSString *)version {
    NSString *version = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
    if (!version.length) {
        version = @"1.0.0";
    }
    return version;
}

- (void)optionalUpdate:(NSString *)title content:(NSString *)content url:(NSString *)url {
    [LTUpgradePopView showWithForce:NO title:title content:content sureHandler:^{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) { }];
    } ignoreHandler:^{
        //不处理
    }];
}

- (void)forceUpdate:(NSString *)title content:(NSString *)content url:(NSString *)url {
    [LTUpgradePopView showWithForce:YES title:title content:content sureHandler:^{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) { }];
    } ignoreHandler:^{
        //不处理
    }];
}

@end
